import base64
import hashlib
import os
import random
import re
import requests
import threading
import time
import string
import json
from functools import wraps

from flask import request, session, Response, Blueprint, jsonify, make_response, render_template, g
from flask_mail import Message

# from app.service.imageFunction import gene_code
# from OperationPlatform.settings import BASE_DIR
# from app.service.sendMailFunction import eMailClass
from sqlalchemy import desc, asc

from app.utils.authority import exception_handling
from .models import *
from app import app, db
from exts import _isLogin, mail
from app.utils.error import ResponseError

from app.utils.time_util import *

UserApi = Blueprint('user_api', __name__, template_folder='templates')


@UserApi.route('/create.do', methods=['post'])
@exception_handling
@_isLogin
def user_create_user_do():
    if str(g.user.role) != '1':
        raise ResponseError(2, '权限不足')
    user = request.values.get('username')
    pwd = request.values.get('password')
    name = request.values.get('name')
    role = request.values.get('role')
    mail = request.values.get('mail')
    if not user or not pwd or str(role) not in ['1', '0']:
        raise ResponseError(1, '关键字为空')
    if QUserInfo.query.get(user):
        raise ResponseError(1, '该账户已存在')
    user = QUserInfo(username=user, name=name, role=role, mail=mail, reg_date=timestamp2datetime(int(time.time())))
    user.hash_password(pwd)
    db.session.add(user)
    db.session.commit()
    return jsonify()


@UserApi.route('/delete.do', methods=['post'])
@exception_handling
@_isLogin
def user_delete_user_do():
    if str(g.user.role) != '1':
        raise ResponseError(2, '权限不足')
    user = request.values.get('username')
    if not user:
        raise ResponseError(1, '关键字为空')
    if user == 'admin':
        raise ResponseError(1, '超级管理员账户不能删除')
    user = QUserInfo.query.get(user)
    if not user:
        raise ResponseError(1, '该账户不存在')
    db.session.delete(user)
    db.session.commit()
    return jsonify()


@UserApi.route('/update.do', methods=['post'])
@exception_handling
@_isLogin
def user_update_user_do():
    if str(g.user.role) != '1':
        raise ResponseError(2, '权限不足')
    user = request.values.get('username')
    name = request.values.get('name')
    role = request.values.get('role')
    mail = request.values.get('mail')
    if not user or str(role) not in ['1', '0']:
        raise ResponseError(1, '关键字为空')
    QUserInfo.query.filter_by(username=user).update({'name': name, 'role': role, 'mail': mail})
    db.session.commit()
    return jsonify()


@UserApi.route('/update_role.do', methods=['post'])
@exception_handling
@_isLogin
def user_update_user_role_do():
    if str(g.user.role) != '1':
        raise ResponseError(2, '权限不足')
    user = request.values.get('username')
    competence = request.values.get('competence')
    QUserInfo.query.filter_by(username=user).update({'competence': competence})
    db.session.commit()
    return jsonify()


@UserApi.route('/update_user.do', methods=['post'])
@exception_handling
@_isLogin
def user_update_user_info_do():
    name = request.values.get('name')
    mail = request.values.get('mail')
    user = g.user
    user.name = name
    user.mail = mail
    db.session.commit()
    return jsonify()


@UserApi.route('/change_password.do', methods=['post'])
@exception_handling
@_isLogin
def user_change_password_do():
    pwd = request.values.get('password')
    newpwd1 = request.values.get('newpwd1')
    newpwd2 = request.values.get('newpwd2')
    if newpwd1 != newpwd2:
        raise ResponseError(1, '新密码不匹配')
    user = g.user
    if not user.verify_password(pwd):
        raise ResponseError(1, '旧密码错误')
    user.hash_password(newpwd1)
    db.session.commit()
    return jsonify()


@UserApi.route('/list.do', methods=['post'])
@exception_handling
@_isLogin
def user_get_list_do():
    if str(g.user.role) != '1':
        raise ResponseError(2, '权限不足')
    users = QUserInfo.query.all()
    return jsonify(data=list(map(lambda x: x.to_dict(), users)))


@UserApi.route('/login_history.do', methods=['post'])
@exception_handling
@_isLogin
def user_get_login_history_do():
    history = QUserLoginHistory.query.filter_by(userid=g.user.username).order_by(desc('time')).all()
    return jsonify(data=list(map(lambda x: x.to_dict(), history)))


@UserApi.route('/info.do', methods=['post'])
@exception_handling
@_isLogin
def user_get_user_info_do():
    return jsonify(data=g.user.to_dict())
